<?php

require_once('templates/class/dao/sql/Connection.class.php');
require_once('templates/class/dao/sql/ConnectionFactory.class.php');
require_once('templates/class/dao/sql/ConnectionProperty.class.php');
require_once('templates/class/dao/sql/QueryExecutor.class.php');
require_once('templates/class/dao/sql/Transaction.class.php');
require_once('templates/class/dao/sql/SqlQuery.class.php');
require_once('templates/class/Template.php');

define('CRLF', chr(13) . chr(10)); // Carriage return line feed
define('TAB', chr(9)); // Carriage return line feed

function generate() {
	init();
	$sql = 'SHOW TABLES';
	$ret = QueryExecutor::execute(new SqlQuery($sql));
	createDomainObjects($ret);
	getnerateDAOObjects($ret);
	getnerateDAOExtObjects($ret);
	getnerateIDAOObjects($ret);
	createIncludeFile($ret);
	createDAOFactory($ret);
}

function init() {
	@mkdir("generated");
	@mkdir("generated/class");
	@mkdir("generated/class/dto");
	@mkdir("generated/class/mysql");
	@mkdir("generated/class/mysql/ext");
	@mkdir("generated/class/sql");
	@mkdir("generated/class/dao");
	@mkdir("generated/class/core");
	copy('templates/class/dao/sql/Connection.class.php', 'generated/class/sql/Connection.class.php');
	copy('templates/class/dao/sql/ConnectionFactory.class.php', 'generated/class/sql/ConnectionFactory.class.php');
	copy('templates/class/dao/sql/ConnectionProperty.class.php', 'generated/class/sql/ConnectionProperty.class.php');
	copy('templates/class/dao/sql/QueryExecutor.class.php', 'generated/class/sql/QueryExecutor.class.php');
	copy('templates/class/dao/sql/Transaction.class.php', 'generated/class/sql/Transaction.class.php');
	copy('templates/class/dao/sql/SqlQuery.class.php', 'generated/class/sql/SqlQuery.class.php');
	copy('templates/class/dao/core/ArrayList.class.php', 'generated/class/core/ArrayList.class.php');
}

function createIncludeFile($ret) {
	$str ='' . CRLF;
	for($i=0;$i<count($ret);$i++) {
		$table_name = $ret[$i][0];
		if (!doesTableContainPK($ret[$i])) {
			continue;
		}
		$class_name = getClassName($table_name);
		$str .= TAB . "require_once 'class/dao/" . $class_name . "DAO.class.php';" . CRLF;
		$str .= TAB . "require_once 'class/dto/" . getDTOName($class_name). ".class.php';" . CRLF;
		$str .= TAB . "require_once 'class/mysql/" . $class_name . "MySqlDAO.class.php';" . CRLF;
		$str .= TAB . "require_once 'class/mysql/ext/" . $class_name . "MySqlExtDAO.class.php';" . CRLF;
	}
	$template = new Template('templates/include_dao.tpl');
	$template->set('include', $str);
	$template->write('generated/include_dao.php');
}

function doesTableContainPK($row) {
	$row = getFields($row[0]);
	for($j=0;$j<count($row);$j++) {
		if ($row[$j][3] ==  'PRI') {
			return true;
		}
	}
	return false;
}

function createDAOFactory($ret) {
	$str ='' . CRLF;
	for($i=0;$i<count($ret);$i++) {
		if (!doesTableContainPK($ret[$i])) {
			continue;
		}
		$table_name = $ret[$i][0];
		$class_name = getClassName($table_name);
		$str .= TAB . "/**" . CRLF;
		$str .= TAB . " * @return " . $class_name . "DAO" . CRLF;
		$str .= TAB . " */" . CRLF;
		$str .= TAB . "public static function get" . $class_name . "DAO() {" . CRLF;
		$str .= TAB . TAB . "return new " . $class_name . "MySqlExtDAO();" . CRLF;
		$str .= TAB . "}" . CRLF . CRLF;
	}
	$template = new Template('templates/DAOFactory.tpl');
	$template->set('content', $str);
	$template->write('generated/class/dao/DAOFactory.class.php');
}

/**
 * Enter description here...
 *
 * @param unknown_type $ret
 * @return
 */
function createDomainObjects($ret) {
	for($i=0;$i<count($ret);$i++) {
		if (!doesTableContainPK($ret[$i])) {
			continue;
		}
		$table_name = $ret[$i][0];
		$class_name = getClassName($table_name);
		//if ($class_name[strlen($class_name)-1] ==  's') {
		//	$class_name = substr($class_name, 0, strlen($class_name)-1);
		//}
		$template = new Template('templates/Domain.tpl');
		$template->set('domain_class_name', $class_name);
		$template->set('table_name', $table_name);
		$tab = getFields($table_name);
		$fields = CRLF;
		for($j=0;$j<count($tab);$j++) {
			$fields .= TAB . "public $" . getVarNameWithS($tab[$j][0]) . ';' . CRLF;
		}
		$template->set('properties', $fields);
		$template->set('date', date("Y-m-d H:i"));
		$template->write('generated/class/dto/' . $class_name . '.class.php');
	}
}

function getnerateDAOExtObjects($ret) {
	for($i=0;$i<count($ret);$i++) {
		if (!doesTableContainPK($ret[$i])) {
			continue;
		}
		$table_name = $ret[$i][0];
		$class_name = getClassName($table_name) . 'MySqlExt';
		$class_name_sup = getClassName($table_name) . 'MySql';
		$template = new Template('templates/DAOExt.tpl');
		$template->set('class_name_dao_sup', $class_name_sup);
		$template->set('class_name_dao', $class_name);
		$template->set('class_name_domain', getDTOName($table_name));
		$template->set('class_name_idao', getClassName($table_name));
		$template->set('table_name', $table_name);
		$template->set('variable_name', getVarName($table_name));
		$tab = getFields($table_name);
		$parameterSetter = '' . CRLF;
		$insertFields = '';
		$updateFields = '';
		$questionMarks = '';
		$readRow = '' . CRLF;
		$pk = '';
		$queryByField = '';
		$deleteByField = '';
		for($j=0;$j<count($tab);$j++) {
			if ($tab[$j][3] ==  'PRI') {
				$pk = $tab[$j][0];
			}else{
				$insertFields .= $tab[$j][0]. ", ";
				$updateFields .= $tab[$j][0]. " = ?, ";
				$questionMarks .= "?, ";
				if (isColumnTypeNumber($tab[$j][1])) {
					$parameterSetter .= TAB . TAB . "\$sqlQuery->setNumber($" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). ');' . CRLF;
				}else{
					$parameterSetter .= TAB . TAB . "\$sqlQuery->set($" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). ');' . CRLF;
				}
				$parameterSetter2 = '';
				if (isColumnTypeNumber($tab[$j][1])) {
					$parameterSetter2 .= "Number";
				}
				$queryByField .= "	public function queryBy" . getClassName($tab[$j][0]). "(\$value) {
		\$sql = 'SELECT * FROM " . $table_name. " WHERE " . $tab[$j][0]. " = ?';
		\$sqlQuery = new SqlQuery(\$sql);
		\$sqlQuery->set" . $parameterSetter2. "(\$value);
		return \$this->getList(\$sqlQuery);
	}" . CRLF . CRLF;
				$deleteByField .= "	public function deleteBy" . getClassName($tab[$j][0]). "(\$value) {
		\$sql = 'DELETE FROM " . $table_name. " WHERE " . $tab[$j][0]. " = ?';
		\$sqlQuery = new SqlQuery(\$sql);
		\$sqlQuery->set" . $parameterSetter2. "(\$value);
		return \$this->executeUpdate(\$sqlQuery);
	}" . CRLF . CRLF;
			}
			$readRow .= TAB . TAB . "\$" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). " = \$row['" . $tab[$j][0]. "'];" . CRLF;
		}
		if ($pk ==  '') {
			continue;
		}
		$insertFields = substr($insertFields,0, strlen($insertFields)-2);
		$updateFields = substr($updateFields,0, strlen($updateFields)-2);
		$questionMarks = substr($questionMarks,0, strlen($questionMarks)-2);
		$template->set('pk', $pk);
		$template->set('pk_php', getVarNameWithS($pk));		
		$template->set('insert_fields', $insertFields);
		$template->set('read_row', $readRow);
		$template->set('update_fields', $updateFields);
		$template->set('question_marks', $questionMarks);
		$template->set('parameter_setter',$parameterSetter);
		$template->set('read_row',$readRow);
		$template->set('date', date("Y-m-d H:i"));
		$template->set('queryByFieldFunctions',$queryByField);		
		$template->set('deleteByFieldFunctions',$deleteByField);	
		$file = 'generated/class/mysql/ext/' . $class_name . 'DAO.class.php';
		if (!file_exists($file)) {
			$template->write('generated/class/mysql/ext/' . $class_name . 'DAO.class.php');
		}
	}
}


function getnerateDAOObjects($ret) {
	for($i=0;$i<count($ret);$i++) {
		if (!doesTableContainPK($ret[$i])) {
			continue;
		}
		$table_name = $ret[$i][0];
		$class_name = getClassName($table_name) . 'MySql';

		$tab = getFields($table_name);
		$parameterSetter = '' . CRLF;
		$insertFields = '';
		$updateFields = '';
		$questionMarks = '';
		$readRow = '' . CRLF;
		$pk = '';
		$pks = array();
		$queryByField = '';
		$deleteByField = '';
		$pk_type= '';
		for($j=0;$j<count($tab);$j++) {
			if ($tab[$j][3] ==  'PRI') {
				$pk = $tab[$j][0];
				$c = count($pks);
				$pks[$c] = $tab[$j][0];
				$pk_type = $tab[$j][1];
			}else{
				$insertFields .= $tab[$j][0]. ", ";
				$updateFields .= $tab[$j][0]. " = ?, ";
				$questionMarks .= "?, ";
				if (isColumnTypeNumber($tab[$j][1])) {
					$parameterSetter .= TAB . TAB . "\$sqlQuery->setNumber($" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). ');' . CRLF;
				}else{
					$parameterSetter .= TAB . TAB . "\$sqlQuery->set($" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). ');' . CRLF;
				}
				$parameterSetter2 = '';
				if (isColumnTypeNumber($tab[$j][1])) {
					$parameterSetter2 .= "Number";
				}
				$queryByField .= "	public function queryBy" . getClassName($tab[$j][0]). "(\$value) {
		\$sql = 'SELECT * FROM " . $table_name. " WHERE " . $tab[$j][0]. " = ?';
		\$sqlQuery = new SqlQuery(\$sql);
		\$sqlQuery->set" . $parameterSetter2. "(\$value);
		return \$this->getList(\$sqlQuery);
	}" . CRLF . CRLF;
				$deleteByField .= "	public function deleteBy" . getClassName($tab[$j][0]). "(\$value) {
		\$sql = 'DELETE FROM " . $table_name. " WHERE " . $tab[$j][0]. " = ?';
		\$sqlQuery = new SqlQuery(\$sql);
		\$sqlQuery->set" . $parameterSetter2. "(\$value);
		return \$this->executeUpdate(\$sqlQuery);
	}" . CRLF . CRLF;
			}
			$readRow .= TAB . TAB . "\$" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). " = \$row['" . $tab[$j][0]. "'];" . CRLF;
		}
		if ($pk ==  '') {
			continue;
		}
		if (count($pks) == 1) {
			$template = new Template('templates/DAO.tpl');
			echo '$pk_type ' . $pk_type . ' <br/>';
			if (isColumnTypeNumber($pk_type)) {
				$template->set('pk_number', 'Number');
			}else{
				$template->set('pk_number', '');
			}
		}else{			
			$template = new Template('templates/DAO_with_complex_pk.tpl');
		}
		$template->set('class_name_dao', $class_name );
		$template->set('class_name_domain', getDTOName($table_name) );
		$template->set('class_name_idao', getClassName($table_name));
		$template->set('table_name', $table_name);
		$template->set('variable_name', getVarName($table_name));
		
		$insertFields = substr($insertFields,0, strlen($insertFields)-2);
		$updateFields = substr($updateFields,0, strlen($updateFields)-2);
		$questionMarks = substr($questionMarks,0, strlen($questionMarks)-2);
		$template->set('pk', $pk);
		$s = '';
		$s2 = '';
		$s3 = '';
		$s4 = '';
		$insertFields2 = $insertFields;
		$questionMarks2 = $questionMarks;
		for($z=0;$z<count($pks);$z++) {
			$questionMarks2.= ', ?';			
			if ($z>0) {
				$s.= ', ';								
				$s2.= ' AND ';
				$s3.= TAB . TAB . '';
			}			
			$insertFields2.= ', ' . $pks[$z];
			$s .= '$'.getVarNameWithS($pks[$z]);
			$s2 .= $pks[$z] . '  = ? ';
			$s3 .= '$sqlQuery->setNumber($'.getVarNameWithS($pks[$z]) . ' );';			
			$s3 .= '' . CRLF;
			$s4 .= CRLF;
			$s4 .= TAB . TAB . '$sqlQuery->setNumber($'.getVarName($table_name) . ' ->'.getVarNameWithS($pks[$z]) . ' );';
			$s4 .= '' . CRLF;
		}
		if ($s[0] ==  ',')$s = substr($s,1);
		if ($questionMarks2[0] ==  ',')$questionMarks2= substr($questionMarks2,1);
		if ($insertFields2[0] ==  ',')$insertFields2= substr($insertFields2,1);
		$template->set('question_marks2', $questionMarks2);
		$template->set('insert_fields2', $insertFields2);
		$template->set('pk_set_update', $s4);
		$template->set('pk_set', $s3);		
		$template->set('pk_where', $s2);
		$template->set('pks', $s);
		$template->set('pk_php', getVarNameWithS($pk));		
		$template->set('insert_fields', $insertFields);
		$template->set('read_row', $readRow);
		$template->set('update_fields', $updateFields);
		$template->set('question_marks', $questionMarks);
		$template->set('parameter_setter',$parameterSetter);
		$template->set('read_row',$readRow);
		$template->set('date', date("Y-m-d H:i"));
		$template->set('queryByFieldFunctions',$queryByField);		
		$template->set('deleteByFieldFunctions',$deleteByField);	
		$template->write('generated/class/mysql/' . $class_name . 'DAO.class.php');
	}
}

function isColumnTypeNumber($columnType) {
	echo $columnType . ' <br/>';
	if (strtolower(substr($columnType,0,3)) ==  'int' || strtolower(substr($columnType,0,7)) ==  'tinyint') {
		return true;
	}
	return false;
}

function getnerateIDAOObjects($ret) {
	for($i=0;$i<count($ret);$i++) {
		if (!doesTableContainPK($ret[$i])) {
			continue;
		}
		$table_name = $ret[$i][0];
		$class_name = getClassName($table_name);
		$tab = getFields($table_name);
		$parameterSetter = '' . CRLF;
		$insertFields = '';
		$updateFields = '';
		$questionMarks = '';
		$readRow = '' . CRLF;
		$pk = '';
		$pks = array();
		$queryByField = '';
		$deleteByField = '';
		for($j=0;$j<count($tab);$j++) {
			if ($tab[$j][3] ==  'PRI') {
				$pk = $tab[$j][0];
				$c = count($pks);
				$pks[$c] = $tab[$j][0];
			}else{
				$insertFields .= $tab[$j][0]. ", ";
				$updateFields .= $tab[$j][0]. " = ?, ";
				$questionMarks .= "?, ";
				if (isColumnTypeNumber($tab[$j][1])) {
					$parameterSetter .= TAB . TAB . "\$sqlQuery->setNumber($" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). ');' . CRLF;
				}else{
					$parameterSetter .= TAB . TAB . '' . ' $sqlQuery->set($'.getVarName($tab[$j][0]) . ' );' . '' . CRLF;
				}
				$queryByField .= TAB . "public function queryBy" . getClassName($tab[$j][0]). "(\$value);" . CRLF . CRLF;
				$deleteByField .= TAB . "public function deleteBy" . getClassName($tab[$j][0]). "(\$value);" . CRLF . CRLF;
			}
			$readRow .= TAB . TAB . "\$" . getVarName($table_name). '->' . getVarNameWithS($tab[$j][0]). " = \$row['" . $tab[$j][0]. "'];" . CRLF;
		}
		if ($pk ==  '') {
			continue;
		}
		
		if (count($pks) == 1) {
			$template = new Template('templates/Interface.tpl');
		}else{			
			$template = new Template('templates/Interface_Complex.tpl');
		}
		
		$template->set('class_name_dao', $class_name);
		$template->set('table_name', $table_name);
		$template->set('variable_name', getVarName($table_name));
		
		$s = '';
		$s2 = '';
		$s3 = '';
		$s4 = '';
		$insertFields2 = $insertFields;
		$questionMarks2 = $questionMarks;
		for($z=0;$z<count($pks);$z++) {
			$questionMarks2.= ', ?';			
			if ($z>0) {
				$s.= ', ';								
				$s2.= ' AND ';
				$s3.= TAB . TAB . '';
			}			
			$insertFields2.= ', '.getVarNameWithS($pks[$z]);
			$s .= '$'.getVarNameWithS($pks[$z]);
			$s2 .= getVarNameWithS($pks[$z]) . '  = ? ';
			$s3 .= '$sqlQuery->setNumber('.getVarName($pks[$z]) . ' );';			
			$s3 .= '' . CRLF;
			$s4 .= "\n\t\t";
			$s4 .= '$sqlQuery->setNumber($'.getVarName($table_name) . ' ->'.getVarNameWithS($pks[$z]) . ' );';
			$s4 .= '' . CRLF;
		}
		$template->set('question_marks2', $questionMarks2);
		$template->set('insert_fields2', $insertFields2);
		$template->set('pk_set_update', $s4);
		$template->set('pk_set', $s3);		
		$template->set('pk_where', $s2);
		$template->set('pks', $s);
		
		$insertFields = substr($insertFields,0, strlen($insertFields)-2);
		$updateFields = substr($updateFields,0, strlen($updateFields)-2);
		$questionMarks = substr($questionMarks,0, strlen($questionMarks)-2);
		$template->set('pk', $pk);
		$template->set('insert_fields', $insertFields);
		$template->set('read_row', $readRow);
		$template->set('update_fields', $updateFields);
		$template->set('question_marks', $questionMarks);
		$template->set('parameter_setter',$parameterSetter);
		$template->set('read_row',$readRow);
		$template->set('date', date("Y-m-d H:i"));
		$template->set('queryByFieldFunctions',$queryByField);
		$template->set('deleteByFieldFunctions',$deleteByField);		
		$template->write('generated/class/dao/' . $class_name . 'DAO.class.php');
	}
}


function getFields($table) {
	$sql = 'DESC ' . $table;
	return QueryExecutor::execute(new SqlQuery($sql));
}


function getClassName($table_name) {
	$table_name = strtoupper($table_name[0]).substr($table_name,1);
	for($i=0;$i<strlen($table_name);$i++) {
		if ($table_name[$i] ==  '_') {
			$table_name = substr($table_name, 0, $i).strtoupper($table_name[$i+1]).substr($table_name, $i+2);
		}
	}
	return $table_name;
}

function getDTOName($table_name) {
	$name = getClassName($table_name);
	//if ($name[strlen($name)-1] ==  's') {
	//	$name = substr($name, 0, strlen($name)-1);
	//}
	return $name;
}

function getVarName($table_name) {
	$table_name = strtolower($table_name[0]).substr($table_name,1);
	for($i=0;$i<strlen($table_name);$i++) {
		if ($table_name[$i] ==  '_') {
			$table_name = substr($table_name, 0, $i).strtoupper($table_name[$i+1]).substr($table_name, $i+2);
		}
	}
	//if ($table_name[strlen($table_name)-1] ==  's') {
	//	$table_name = substr($table_name, 0, strlen($table_name)-1);
	//}
	return $table_name;
}


function getVarNameWithS($table_name) {
	$table_name = strtolower($table_name[0]).substr($table_name,1);
	for($i=0;$i<strlen($table_name);$i++) {
		if ($table_name[$i] ==  '_') {
			$table_name = substr($table_name, 0, $i).strtoupper($table_name[$i+1]).substr($table_name, $i+2);
		}
	}
	//if ($table_name[strlen($table_name)-1] ==  's') {
	//	$table_name = substr($table_name, 0, strlen($table_name)-1);
	//}
	return $table_name;
}


generate();



?>